package com.lingxu.base.config;

import com.lingxu.base.common.constant.CacheConstant;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.time.Duration;
import java.util.Arrays;

import static java.util.Collections.singletonMap;

@Configuration
@EnableCaching // 开启缓存支持
public class RedisConfig extends CachingConfigurerSupport {

	@Resource
	private LettuceConnectionFactory lettuceConnectionFactory;

	/**
	 * 自定义的缓存key的生成策略 若想使用这个key
	 * 只需要将注解Cacheable上keyGenerator的值设置为selfKeyGenerator（即方法名）即可</br>
	 * @return 自定义策略生成的key
	 */
	@Bean
	public KeyGenerator selfKeyGenerator() {
		return new KeyGenerator() {
			@Override
			public Object generate(Object target, Method method, Object... params) {
				StringBuilder sb = new StringBuilder();
				sb.append(target.getClass().getName());
				sb.append(method.getDeclaringClass().getName());
				Arrays.stream(params).map(Object::toString).forEach(sb::append);
				return sb.toString();
			}
		};
	}

	/**
	 * RedisTemplate配置
	 *
	 * @param lettuceConnectionFactory
	 * @return
	 */
	@Bean
	public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
		RedisTemplate<String, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(lettuceConnectionFactory);
		// 将 key 序列化成字符串
		template.setKeySerializer(new StringRedisSerializer());
		// 将 hash 的 key 序列化成字符串
		template.setHashKeySerializer(new StringRedisSerializer());
		// 将 value 序列化成 json
//        template.setValueSerializer(jacksonSerializer);
		template.setValueSerializer(new GenericJackson2JsonRedisSerializer());

		// 将 hash 的 value 序列化成 json
		template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

		template.afterPropertiesSet();
		return template;
	}

	/**
	 * 缓存配置管理器
	 *
	 * @param factory
	 * @return
	 */
	@Bean
	public CacheManager cacheManager(LettuceConnectionFactory factory) {
		/* 默认配置，设置缓存有效期 6小时*/
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
				.entryTtl(Duration.ofHours(6));
		/* 配置序列化*/
		RedisCacheConfiguration redisCacheConfiguration = config
				.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
				.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        
		// 以锁写入的方式创建RedisCacheWriter对象
		//RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(factory);

		// 创建默认缓存配置对象
		/* 自定义配置test:demo 的超时时间为 5分钟*/
		/* 新增自定义配置需在构造过程中 加入更多的withInitialCacheConfigurations*/
		RedisCacheManager cacheManager = RedisCacheManager
				.builder(RedisCacheWriter.lockingRedisCacheWriter(factory))
				.cacheDefaults(redisCacheConfiguration)
				.withInitialCacheConfigurations(
						singletonMap(
								CacheConstant.TEST_DEMO_CACHE,
								RedisCacheConfiguration.defaultCacheConfig().
										entryTtl(Duration.ofMinutes(5)).disableCachingNullValues()
						)
				)
				.withInitialCacheConfigurations(
						singletonMap(
								CacheConstant.SYS_USERS_LOGIN_CACHE,
								RedisCacheConfiguration.defaultCacheConfig().
										entryTtl(Duration.ofMinutes(5)).disableCachingNullValues()
						)
				)

				.transactionAware().build();
		return cacheManager;
	}

}
